package com.guodi.model.controller;

import com.guodi.common.utils.*;
import com.guodi.core.tool.api.R;
import com.guodi.model.entity.User;
import com.guodi.model.service.IUserService;
import com.guodi.model.utils.ConvertUtil;
import com.guodi.model.vo.ApiCimUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/General")
@Api(value = "API - GeneralController", tags = "通行模块（用于对接CIM平台）")
public class GeneralController {

    private static Logger logger = LoggerFactory.getLogger(GeneralController.class);

    @Resource
    public IUserService userService;

    /**
     * @描述: 用于对接CIM平台登录用户的解析
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/21 17:16
     **/
    @GetMapping("/getNameByToken")
    @ApiOperation(value = "解析CIM平台管理用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "token", required = true, dataType = "string", paramType = "query")
    })
    public R getNameByToken(HttpServletRequest request) throws Exception {
        String token = request.getQueryString().replaceAll("token=", "");
        logger.info("接收cim平台系统token为：" + token);
        token = URLDecoder.decode(token, "UTF-8");
        if (StringUtils.isEmpty(token)) {
            return R.fail("认证失败");
        }
        //空格替换成+号
        token = token.replaceAll(" ", "+");
        String key = MDUtil.getMessageDigest("Cim@202304".getBytes(StandardCharsets.UTF_8), "MD5");
        String decrypted = new String(AESUtil.aesDecrypt(Base64.getDecoder().decode(token), key.getBytes(StandardCharsets.UTF_8)), "UTF8");
        String[] items = decrypted.split("\\|");
        //dhj修改，这里需要处理,将后面的零去掉
        String regionCode = items[3];
        regionCode = ConvertUtil.removeLastZero(regionCode);
        userService.authentication(items[1], regionCode);
        return R.data(items[1]);
    }

    /**
     * @描述: 新增CIM平台管理用户
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/20 11:07
     **/
    @RequestMapping("/saveCimUser")
    @ApiOperation(value = "新增CIM平台管理用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "regionCode", value = "行政区划代码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别(0:女 1:男)", required = false, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "identityCard", value = "身份证号码", required = false, dataType = "string", paramType = "query")
    })
    public R saveCimUser(@ApiIgnore ApiCimUser user) {
        if (StringUtils.isEmpty(user.getAccount())) {
            return R.fail("账号不可为空");
        }
        if (StringUtils.isEmpty(user.getUserName())) {
            return R.fail("用户名不可为空");
        }
        if (StringUtils.isEmpty(user.getRegionCode())) {
            return R.fail("行政区划代码不可为空");
        }
        List<User> list = getUserByAccount(user.getAccount());
        if (!CollectionUtils.isEmpty(list)) {
            return R.fail("账号已存在！");
        }
        userService.saveCimUser(user);
        userService.refreshRedis();
        return R.data(user);
    }

    /**
     * @描述: 编辑CIM平台管理用户
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/20 11:07
     **/
    @RequestMapping("/editCimUser")
    @ApiOperation(value = "编辑CIM平台管理用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "userName", value = "用户名", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "regionCode", value = "行政区划代码", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "sex", value = "性别(0:女 1:男)", required = false, dataType = "Integer", paramType = "query"),
    })
    public R editCimUser(@ApiIgnore ApiCimUser cimUser) {
        if (StringUtils.isEmpty(cimUser.getAccount())) {
            return R.fail("账号不可为空");
        }
        List<User> list = getUserByAccount(cimUser.getAccount());
        if (CollectionUtils.isEmpty(list)) {
            return R.fail("账号不存在！");
        }
        User user = list.get(0);
        userService.editCimUser(cimUser, user);
        userService.refreshRedis();
        return R.data("修改成功");
    }

    /**
     * @描述: 删除CIM平台管理用户
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/20 11:07
     **/
    @RequestMapping("/delCimUser")
    @ApiOperation(value = "删除CIM平台管理用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "account", value = "账号", required = true, dataType = "string", paramType = "query")
    })
    public R delCimUser(String account) {
        if (StringUtils.isEmpty(account)) {
            return R.fail("账号不可为空");
        }
        List<User> list = getUserByAccount(account);
        if (CollectionUtils.isEmpty(list)) {
            return R.fail("账号不存在！");
        }
        userService.delCimUser(list.get(0));
        return R.data("删除成功");
    }

    /**
     * @描述: 根据账号获取用户信息
     * @入参:
     * @出参:
     * @作者: lzy
     * @日期: 2023/4/23 16:50
     **/
    private List<User> getUserByAccount(String account) {
        Map map = new HashMap();
        map.put("USER_CODE", account);
        map.put("IS_DELETED", 0);
        List<User> list = userService.listByMap(map);
        return list;
    }
}
